#ifndef XG_WEBX_SESS_H
#define XG_WEBX_SESS_H
///////////////////////////////////////////////////////////
#include <functional>
#include <json/json.h>
#include <http/HttpServer.h>
#include <http/HttpRequest.h>
#include <dbx/RedisConnect.h>
#include "../dbentity/T_XG_USER.h"

class LoginToken : public Object
{
private:
	string sid;
	string user;
	string dbid;
	string name;
	string icon;
	string mail;
	string phone;
	string grouplist;
	sp<Session> session;
	HttpDataNode extdata;

public:
	bool check();
	bool update();
	string toString() const;
	JsonElement toJson() const;
	bool update(CT_XG_USER& tab);
	int checkTimes(int maxtimes = 10);

	static sp<LoginToken> Get(const string& sid);
	static sp<LoginToken> Create(long timeout, int minlen = 64);

	bool disable()
	{
		return session && session->disable();
	}
	void clearExtdata()
	{
		extdata.clear();
	}
	LoginToken(sp<Session> sess)
	{
		if (session = sess) sid = sess->getName();
	}
	const string& getUser() const
	{
		return user;
	}
	const string& getName() const
	{
		return name;
	}
	const string& getIcon() const
	{
		return icon;
	}
	const string& getMail() const
	{
		return mail;
	}
	const string& getPhone() const
	{
		return phone;
	}
	const string& getDataId() const
	{
		return dbid;
	}
	const string& getSessionId() const
	{
		return sid;
	}
	const string& getGrouplist() const
	{
		return grouplist;
	}

	bool setTimeout(long timeout)
	{
		return session && session->setTimeout(timeout);
	}
	void setUser(const string& user)
	{
		this->user = user;
	}
	void setName(const string& name)
	{
		this->name = name;
	}
	void setIcon(const string& icon)
	{
		this->icon = icon;
	}
	void setMail(const string& mail)
	{
		this->mail = mail;
	}
	void setPhone(const string& phone)
	{
		this->phone = phone;
	}
	void setDataId(const string& dbid)
	{
		this->dbid = dbid;
	}
	void setGrouplist(const string& grouplist)
	{
		this->grouplist = grouplist;
	}
	string getExtdata(const string& key) const
	{
		return extdata.getValue(key);
	}
	void setExtdata(const string& key, const string& val)
	{
		extdata.setValue(key, val);
	}
};

namespace webx
{
	string GetSessionId(HttpRequest* request);
	sp<Session> GetSession(const string& key, int timeout = 0);
	void SetSessionId(HttpResponse* response, const string& sid);
	sp<Session> GetLocaleSession(const string& key, int timeout = 0);
};
///////////////////////////////////////////////////////////
#endif